<template>
  <div class="station-container">
    <div class="page-header">
      <h2>站点管理</h2>
    </div>
    
    <el-card class="main-card">
      <!-- 操作栏 -->
      <div class="operation-bar">
        <div class="search-box">
          <el-input
            v-model="searchForm.stationName"
            placeholder="请输入站点名称搜索"
            prefix-icon="el-icon-search"
            clearable
            @clear="handleSearch"
            @keyup.enter.native="handleSearch"
          >
          </el-input>
          <el-button type="primary" @click="handleSearch" icon="el-icon-search">搜索</el-button>
        </div>
        <el-button type="success" icon="el-icon-plus" @click="showAddDialog">新增站点</el-button>
      </div>

      <!-- 站点列表 -->
      <el-table
        :data="stations"
        style="width: 100%"
        border
        stripe
      >
        <el-table-column prop="stationName" label="站点名称" width="120"></el-table-column>
        <el-table-column prop="chiefName" label="负责人" width="100"></el-table-column>
        <el-table-column label="地址" min-width="250">
          <template slot-scope="scope">
            {{ scope.row.city }}{{ scope.row.district }}{{ scope.row.street }}{{ scope.row.detailedAddress }}
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="联系电话" width="120"></el-table-column>
        <el-table-column label="营业时间" width="200">
          <template slot-scope="scope">
            {{ formatTime(scope.row.openingTime) }} - {{ formatTime(scope.row.closingTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="rating" label="评分" width="80">
          <template slot-scope="scope">
            {{ scope.row.rating || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
              {{ scope.row.status === 1 ? '正常' : '关闭' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="showStationDetail(scope.row)"
            >详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchForm.pageNum"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="searchForm.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 新增站点对话框 -->
    <el-dialog
      title="新增站点"
      :visible.sync="dialogVisible"
      width="60%"
      :close-on-click-modal="false"
    >
      <el-form :model="stationForm" :rules="formRules" ref="stationForm" label-width="100px">
        <el-form-item label="站点名称" prop="stationName">
          <el-input v-model="stationForm.stationName"></el-input>
        </el-form-item>
        <el-form-item label="负责人" prop="chiefName">
          <el-select v-model="stationForm.chiefName" placeholder="请选择负责人" style="width: 100%">
            <el-option
              v-for="name in unassignedAccounts"
              :key="name"
              :label="name"
              :value="name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="stationForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="地址选择" required>
          <el-button type="primary" @click="showMapDialog">选择地址</el-button>
          <div class="address-preview" v-if="stationForm.city">
            {{ stationForm.city }}{{ stationForm.district }}{{ stationForm.street }}{{ stationForm.detailedAddress }}
          </div>
        </el-form-item>
        <el-form-item label="营业时间" required>
          <el-time-picker
            v-model="stationForm.openingTime"
            format="HH:mm"
            placeholder="开始时间"
          ></el-time-picker>
          <span class="time-separator">-</span>
          <el-time-picker
            v-model="stationForm.closingTime"
            format="HH:mm"
            placeholder="结束时间"
          ></el-time-picker>
        </el-form-item>
        <el-form-item label="站点介绍">
          <el-input
            type="textarea"
            :rows="3"
            v-model="stationForm.stationIntroduction"
          ></el-input>
        </el-form-item>
        <el-form-item label="站点Logo">
          <el-upload
            class="avatar-uploader"
            action="/upload"
            :show-file-list="false"
            :on-success="handleLogoSuccess"
            :before-upload="beforeLogoUpload"
          >
            <img v-if="stationForm.stationLogo" :src="stationForm.stationLogo" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 地图选择对话框 -->
    <el-dialog
      title="选择地址"
      :visible.sync="mapDialogVisible"
      width="70%"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      @closed="handleMapDialogClose"
    >
      <div class="map-container">
        <div class="map-tools">
          <el-input
            v-model="searchAddress"
            placeholder="输入地址搜索，按回车或点击搜索按钮"
            class="search-input"
            @keyup.enter.native="searchMapLocation"
          >
            <el-button slot="append" icon="el-icon-search" @click="searchMapLocation">搜索</el-button>
          </el-input>
          <div class="map-tip">
            <p><i class="el-icon-info"></i> 操作提示：</p>
            <p>1. 直接点击地图选择位置</p>
            <p>2. 输入地址搜索定位</p>
            <p>3. 拖动红色标记微调位置</p>
          </div>
          <div class="selected-address" v-if="stationForm.city">
            <p><strong>已选位置：</strong></p>
            <p>{{ stationForm.city }}{{ stationForm.district }}{{ stationForm.street }}{{ stationForm.detailedAddress }}</p>
          </div>
        </div>
        <div id="map" class="map-content"></div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="mapDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmLocation">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 站点详情对话框 -->
    <el-dialog
      title="站点详情"
      :visible.sync="detailDialogVisible"
      width="65%"
      class="station-detail-dialog"
    >
      <div class="station-detail">
        <div class="detail-header">
          <div class="station-logo">
            <img v-if="currentStation.stationLogo" :src="currentStation.stationLogo" alt="站点Logo">
            <div v-else class="default-logo">
              {{ getLogoText(currentStation.stationName) }}
            </div>
          </div>
          <div class="station-basic">
            <div class="station-title">
              <h3>{{ currentStation.stationName }}</h3>
              <el-tag :type="currentStation.status === 1 ? 'success' : 'info'" size="medium">
                {{ currentStation.status === 1 ? '正常营业' : '暂停营业' }}
              </el-tag>
            </div>
            <div class="station-brief">
              <span class="brief-item">
                <i class="el-icon-user"></i>
                {{ currentStation.chiefName }}
              </span>
              <span class="brief-item">
                <i class="el-icon-phone"></i>
                {{ currentStation.phone || '-' }}
              </span>
              <span class="brief-item">
                <i class="el-icon-time"></i>
                {{ formatTime(currentStation.openingTime) }} - {{ formatTime(currentStation.closingTime) }}
              </span>
            </div>
          </div>
        </div>
        
        <el-divider content-position="left">详细信息</el-divider>
        
        <div class="detail-content">
          <el-row :gutter="20">
            <el-col :span="24">
              <div class="info-block">
                <div class="info-title">
                  <i class="el-icon-location"></i>
                  站点地址
                </div>
                <div class="info-content address-content">
                  {{ currentStation.city }}{{ currentStation.district }}{{ currentStation.street }}{{ currentStation.detailedAddress }}
                </div>
              </div>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="info-block">
                <div class="info-title">
                  <i class="el-icon-star-on"></i>
                  站点评分
                </div>
                <div class="info-content">
                  <el-rate
                    v-model="stationRating"
                    disabled
                    show-score
                    text-color="#ff9900"
                  >
                  </el-rate>
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-block">
                <div class="info-title">
                  <i class="el-icon-date"></i>
                  注册时间
                </div>
                <div class="info-content">
                  {{ formatDate(currentStation.registrationDate) }}
                </div>
              </div>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="24">
              <div class="info-block">
                <div class="info-title">
                  <i class="el-icon-document"></i>
                  站点介绍
                </div>
                <div class="info-content description-content">
                  {{ currentStation.stationIntroduction || '暂无介绍' }}
                </div>
              </div>
            </el-col>
          </el-row>
          
          <!-- <el-row :gutter="20">
            <el-col :span="24">
              <div class="info-block">
                <div class="info-title">
                  <i class="el-icon-map-location"></i>
                  地理位置
                </div>
                <div class="info-content">
                  <div id="detail-map" class="detail-map"></div>
                </div>
              </div>
            </el-col>
          </el-row> -->
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'StationManagement',
  data() {
    return {
      // 搜索表单
      searchForm: {
        pageNum: 1,
        pageSize: 10,
        stationName: ''
      },
      
      // 站点列表
      stations: [],
      total: 0,
      
      // 对话框控制
      dialogVisible: false,
      mapDialogVisible: false,
      detailDialogVisible: false,
      
      // 地图相关
      map: null,
      searchAddress: '',
      selectedLocation: null,
      
      // 表单数据
      stationForm: {
        stationName: '',
        city: '',
        district: '',
        street: '',
        detailedAddress: '',
        latitude: null,
        longitude: null,
        phone: '',
        chiefName: '',
        stationIntroduction: '',
        openingTime: '',
        closingTime: '',
        stationLogo: ''
      },
      
      // 添加未分配人员列表
      unassignedAccounts: [],
      
      // 详情对话框相关
      currentStation: {},
      detailMap: null,
      
      // 表单验证规则
      formRules: {
        stationName: [
          { required: true, message: '请输入站点名称', trigger: 'blur' }
        ],
        chiefName: [
          { required: true, message: '请输入负责人姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ]
      }
    }
  },
  
  mounted() {
    this.fetchStations()
    this.initMap()
  },
  
  methods: {
    // 获取站点列表
    async fetchStations() {
      try {
        const res = await this.$http.get('/platform/recycleBin/selectAllStation', {
          params: {
            pageNum: this.searchForm.pageNum,
            pageSize: this.searchForm.pageSize,
            stationName: this.searchForm.stationName
          }
        })
        if (res.data.code === 200) {
          this.stations = res.data.data.list.reverse()
          this.total = res.data.data.total
        }
      } catch (error) {
        console.error('获取站点列表失败：', error)
      }
    },
    
    // 搜索
    handleSearch() {
      this.searchForm.pageNum = 1
      this.fetchStations()
    },
    
    // 分页
    handleSizeChange(val) {
      this.searchForm.pageSize = val
      this.fetchStations()
    },
    
    handleCurrentChange(val) {
      this.searchForm.pageNum = val
      this.fetchStations()
    },
    
    // 格式化时间
    formatTime(time) {
      if (!time) return '-'
      return time.substring(11, 16)
    },
    
    // 显示新增对话框
    showAddDialog() {
      this.dialogVisible = true
      this.stationForm = {
        stationName: '',
        city: '',
        district: '',
        street: '',
        detailedAddress: '',
        latitude: null,
        longitude: null,
        phone: '',
        chiefName: '',
        stationIntroduction: '',
        openingTime: '',
        closingTime: '',
        stationLogo: ''
      }
      // 获取未分配人员列表
      this.fetchUnassignedAccounts()
    },
    
    // 获取未分配人员列表
    async fetchUnassignedAccounts() {
      try {
        const res = await this.$http.get('/platform/account/selectAccountNoRole')
        if (res.data.code === 200) {
          this.unassignedAccounts = res.data.data
        } else {
          this.$message.error('获取未分配人员列表失败')
        }
      } catch (error) {
        console.error('获取未分配人员列表失败：', error)
        this.$message.error('获取未分配人员列表失败')
      }
    },
    
    // 初始化地图
    initMap() {
      // 确保地图容器存在且AMap已加载
      if (!window.AMap) {
        this.$message.error('地图加载失败，请刷新页面重试')
        return
      }

      this.$nextTick(() => {
        // 创建地图实例
        this.map = new AMap.Map('map', {
          zoom: 12,
          center: [106.504962, 29.533155], // 重庆中心坐标
        })

        // 创建标记点
        this.marker = new AMap.Marker({
          position: new AMap.LngLat(106.504962, 29.533155),
          draggable: true,
          cursor: 'move',
          animation: 'AMAP_ANIMATION_DROP'
        })

        // 添加标记到地图
        this.map.add(this.marker)

        // 添加地图控件
        this.map.addControl(new AMap.Scale())
        this.map.addControl(new AMap.ToolBar())

        // 点击地图事件
        this.map.on('click', (e) => {
          const lnglat = e.lnglat
          this.selectedLocation = lnglat
          this.marker.setPosition(lnglat)
          this.updateLocationInfo(lnglat)
        })

        // 拖动标记结束事件
        this.marker.on('dragend', () => {
          const position = this.marker.getPosition()
          this.selectedLocation = position
          this.updateLocationInfo(position)
        })

        // 添加定位插件
        AMap.plugin('AMap.Geolocation', () => {
          const geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,
            timeout: 10000,
            buttonPosition: 'RB',
            buttonOffset: new AMap.Pixel(10, 20),
            zoomToAccuracy: true
          })
          this.map.addControl(geolocation)
        })
      })
    },
    
    // 显示地图对话框
    showMapDialog() {
      this.mapDialogVisible = true
      this.$nextTick(() => {
        // 如果地图实例不存在，则初始化
        if (!this.map) {
          this.initMap()
        } else {
          // 如果已存在，则调整大小并清除之前的标记
          this.map.resize()
        }
      })
    },
    
    // 搜索地图位置
    searchMapLocation() {
      if (!this.searchAddress) {
        this.$message.warning('请输入搜索地址')
        return
      }

      AMap.plugin(['AMap.PlaceSearch'], () => {
        const placeSearch = new AMap.PlaceSearch({
          city: '全国',
          citylimit: false
        })

        placeSearch.search(this.searchAddress, (status, result) => {
          if (status === 'complete' && result.poiList.pois.length > 0) {
            const poi = result.poiList.pois[0]
            const position = new AMap.LngLat(poi.location.lng, poi.location.lat)
            
            // 移动地图中心点
            this.map.setCenter(position)
            
            // 更新标记位置
            this.marker.setPosition(position)
            
            // 保存选中位置并更新地址信息
            this.selectedLocation = position
            this.updateLocationInfo(position)
          } else {
            this.$message.error('未找到该地址')
          }
        })
      })
    },
    
    // 更新位置信息
    updateLocationInfo(location) {
      AMap.plugin(['AMap.Geocoder'], () => {
        const geocoder = new AMap.Geocoder({
          radius: 1000,
          extensions: 'all'
        })

        geocoder.getAddress([location.lng, location.lat], (status, result) => {
          if (status === 'complete' && result.regeocode) {
            const addressComponent = result.regeocode.addressComponent
            this.stationForm.city = addressComponent.city || addressComponent.province
            this.stationForm.district = addressComponent.district
            this.stationForm.street = addressComponent.township
            this.stationForm.detailedAddress = result.regeocode.formattedAddress
            this.stationForm.latitude = location.lat
            this.stationForm.longitude = location.lng

            // 显示选中成功提示
            this.$message.success('位置选择成功')
          } else {
            this.$message.error('获取地址信息失败')
          }
        })
      })
    },
    
    // 确认位置选择
    confirmLocation() {
      if (!this.selectedLocation) {
        this.$message.warning('请先在地图上选择位置')
        return
      }
      this.mapDialogVisible = false
    },
    
    // Logo 上传
    handleLogoSuccess(res, file) {
      this.stationForm.stationLogo = res.url
    },
    
    beforeLogoUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('只能上传图片文件!')
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!')
      }
      return isImage && isLt2M
    },
    
    // 提交表单
    handleSubmit() {
      this.$refs.stationForm.validate(async valid => {
        if (valid) {
          try {
            const res = await this.$http.post('/platform/recycleBin/addRecycleBin', this.stationForm)
            if (res.data.code === 200) {
              this.$message.success('添加成功')
              this.dialogVisible = false
              this.fetchStations()
            } else {
              this.$message.error(res.data.message || '添加失败')
            }
          } catch (error) {
            this.$message.error('添加失败')
          }
        }
      })
    },
    
    // 处理地图对话框关闭
    handleMapDialogClose() {
      if (this.map) {
        this.map.destroy()
        this.map = null
      }
      this.selectedLocation = null
      this.searchAddress = ''
    },
    
    // 显示站点详情
    showStationDetail(station) {
      this.currentStation = { ...station }
      this.detailDialogVisible = true
      
      // 在下一个 tick 初始化地图
      this.$nextTick(() => {
        this.initDetailMap()
      })
    },
    
    // 初始化详情地图
    initDetailMap() {
      if (!this.currentStation.latitude || !this.currentStation.longitude) {
        return
      }
      
      if (this.detailMap) {
        this.detailMap.destroy()
      }
      
      this.detailMap = new AMap.Map('detail-map', {
        zoom: 14,
        center: [this.currentStation.longitude, this.currentStation.latitude]
      })
      
      // 添加标记
      new AMap.Marker({
        position: [this.currentStation.longitude, this.currentStation.latitude],
        map: this.detailMap
      })
    },
    
    // 获取Logo文字
    getLogoText(stationName) {
      if (!stationName) return '站'
      return stationName.substring(0, 1)
    },
    
    // 格式化日期
    formatDate(date) {
      if (!date) return '-'
      return date.split('T')[0]
    },
    
    // 在 data 中添加计算后的评分
    computed: {
      stationRating() {
        return this.currentStation.rating ? this.currentStation.rating / 20 : 0
      }
    }
  }
}
</script>

<style scoped>
.station-container {
  padding: 20px;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-box {
  display: flex;
  gap: 10px;
}

.search-box .el-input {
  width: 300px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.time-separator {
  margin: 0 10px;
}

.address-preview {
  margin-top: 10px;
  color: #606266;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.map-container {
  position: relative;
  background: #fff;
  border-radius: 4px;
}

.map-tools {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 100;
  width: 300px;
  background: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.search-input {
  margin-bottom: 15px;
}

.map-tip {
  font-size: 12px;
  color: #606266;
  margin-bottom: 15px;
}

.map-tip p {
  margin: 5px 0;
  line-height: 1.4;
}

.selected-address {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #EBEEF5;
  font-size: 12px;
  color: #409EFF;
}

.selected-address p {
  margin: 5px 0;
  line-height: 1.4;
}

.map-content {
  height: 500px;
  width: 100%;
  border-radius: 4px;
}

.station-detail-dialog {
  .el-dialog__body {
    padding: 0;
  }
}

.station-detail {
  padding: 20px;
}

.detail-header {
  display: flex;
  align-items: flex-start;
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.station-logo {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  overflow: hidden;
  margin-right: 24px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.default-logo {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #409EFF, #36D1DC);
  color: white;
  font-size: 48px;
  font-weight: bold;
}

.station-basic {
  flex: 1;
}

.station-title {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

.station-title h3 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.station-brief {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.brief-item {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #606266;
  font-size: 14px;
}

.brief-item i {
  color: #909399;
}

.info-block {
  margin-bottom: 24px;
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.05);
}

.info-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.info-title i {
  color: #409EFF;
}

.info-content {
  color: #606266;
  line-height: 1.6;
}

.address-content {
  background: #f8f9fa;
  padding: 12px;
  border-radius: 4px;
  font-size: 14px;
}

.description-content {
  white-space: pre-wrap;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 4px;
  min-height: 60px;
}

.detail-map {
  height: 300px;
  margin-top: 8px;
  border-radius: 4px;
  border: 1px solid #EBEEF5;
}

.el-divider__text {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}
</style> 